package org.osiris.server.engine;



import java.util.Properties;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

public class MailEngine{

	public static Logger logger=Logger.getLogger(MailEngine.class);

	public static boolean enviarMensaje(String destinatario,String asunto,String cuerpoPlano,String cuerpoHTML){
		try{
			Properties properties = System.getProperties();
			properties.put("mail.transport.protocol", "smtp");
			properties.put("mail.smtp.host", "192.168.10.34"); 
			properties.setProperty("mail.smtp.user", "rfef\\amartinez");
			properties.setProperty("mail.smtp.auth", "true");
			properties.put("mail.debug", "true");
			Session session = Session.getInstance(properties,new javax.mail.Authenticator()
			{
				protected PasswordAuthentication getPasswordAuthentication()
				{
					return new PasswordAuthentication("rfef\\amartinez","qwerty");
				}
			});
			MimeMessage mensaje = new MimeMessage(session);			
			MimeBodyPart messageBodyPart = new MimeBodyPart();    	
			messageBodyPart.setContent(cuerpoHTML,"text/html");
			MimeBodyPart messageBodyPart2 = new MimeBodyPart();    	
			messageBodyPart2.setText(cuerpoPlano);
			Multipart multipart = new MimeMultipart();
			multipart.addBodyPart(messageBodyPart);
			multipart.addBodyPart(messageBodyPart2);
			mensaje.setContent(multipart);    	
			mensaje.setFrom(new InternetAddress("fenix@rfef.es"));
			mensaje.addRecipient(Message.RecipientType.TO, new InternetAddress(destinatario));
			mensaje.setSubject(asunto);
			session.setDebug(true); 
			try{
				Transport mta = session.getTransport();
				mta.connect("rfef\\amartinez","qwerty");
				try{
					mta.sendMessage(mensaje,mensaje.getAllRecipients());
				}catch(SendFailedException ex){return false;}
				mta.close();
			}catch(Exception ex){
				ex.printStackTrace();
				logger.info("Cartero: Error al enviar "+ex.toString());
			}
		}catch(Exception ex){
			ex.printStackTrace();
			return false;}

		return true;
	}
}

